import request from 'request';
import config from './production-config.js';

export default class adapter {
    constructor(req, res) {
        let options = {};
        if ("GET" == req.method) {
            options = {
                method: "GET",
                url: config.globalHost + req.url,
                headers: {
                    'cache-control': 'no-cache',
                    'content-type': 'application/x-www-form-urlencoded',
                    'cookie': req.cookie
                }
            };
        } else if ("POST" == req.method) {
            options = {
                method: "POST",
                url: config.globalHost + req.url,
                headers: {
                    'cache-control': 'no-cache',
                    'content-type': 'application/x-www-form-urlencoded',
                    'cookie': req.cookie
                },
                form: req.body
            };
        }
        request(options, function(error, response, body) {
            if (error) throw new Error(error);
            try {
                res.status(200).send(JSON.parse(body));
            } catch (e) {
                console.log("--------------------json parse error--------------------");
                console.log("resquest options|||",options);
                console.log("response body|||",body);
                console.log("error|||",e);
                console.log("--------------------json parse error--------------------");
                res.status(200).send({code:"1",res:{msg:"json parse error: " + options.url}});
            }
        });
    }
}
